<?php

namespace app\api\controller;

use app\api\service\WechatSubscribeService;
use app\model\Money;
use app\model\PayRecord;
use think\facade\Log;
use think\facade\Request;
use app\common\Common;
use app\api\service\WechatService;

class Wx extends Base
{
    private $service;

    public function __construct(WechatService $service)
    {
        $this->service = $service;
    }

    /**
     * 添加订阅消息用户
     */
    public function addSubscribe()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Video::class)->scene('add_subscribe')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $data = $this->service->addSubscriptionMessageReminder($params['video_id'], $this->getUserID());

        if (empty($data)) {
            return Common::fail();
        }
        return Common::success($data);
    }

    /**
     * 微信小程序充值
     * 
     * @dateTime 2022/09/22
     * @author zhixiang0215@126.com
     * @param array
     * @return json
     */
    public function payBookCurrency()
    {
        $params = Request::param();
        flog([
            'message' => '小程序支付请求参数',
            'params' => $params,
        ],'wechat_pay');
        $uid = $this->getUserID();
        $paymentBlacklist = array_filter(explode(',',config('enum.user_payment_blacklist')));
        if (!empty($paymentBlacklist) && in_array($uid,$paymentBlacklist)){
            $data = [
                'nonceStr' => WechatService::generateRandomString(32,'mixed'),
                'package' => 'prepay_id=' . rand(1,1999),
                'paySign' => WechatService::generateRandomString(32),
                'timeStamp' => time(),
                'signType' => 'RSA',
                'out_trade_no' => Common::Snowflake()//date('YmdHis') . rand(1000, 10000)
            ];
            return Common::success($data);
        }
        $isNewPay = $this->service->isTrue($params['is_new_pay'] ?? false);
        if ($isNewPay){
            $data = $this->service->wechatUnifyPayNew($params, $uid);
        }else{
            $data = $this->service->wechatUnifyPay($params, $uid);
        }
        // $data = $this->service->wechatThirdPartyAppletPayment($params, $this->getUserID()); // 第三方通道支付
        if (!empty($data['message'])) {
            return Common::fail($data['message']);
        }
        return Common::success($data);
    }

    // 米花第三方
    public function thirdPay()
    {
        $params = Request::param();
        $data = $this->service->wechatThirdPartyAppletPayment1($params, $this->getUserID()); // 传化第三方通道支付
        if (!empty($data['message'])) {
            return Common::fail($data['message']);
        }
        return Common::success($data);
    }

    // 微信H5支付
    public function wechatH5Pay()
    {
        $params = Request::param();
        return Common::success();
    }

    /**
     * 微信支付回调
     * 
     * @dateTime 2022/09/22
     * @author zhixiang0215@126.com
     * @param xml
     * @return xml
     */
    public function callback()
    {
        $params = file_get_contents('php://input');
        flog([
            'message' => '微信支付回调-旧',
            'params' => $params,
        ],'wechat_pay');

        $bool = $this->service->wechatPayCallBack($params);

        if (!$bool) {
            echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>';
            exit();
        }

        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        exit();
    }

    /**
     * 掌中付第三方支付回调
     * 
     * @dateTime 2023/02/02
     * @author zhixiang0215@126.com
     * @return string
     */
    public function thirdPartyCallback()
    {
        $params = Request::param();
        flog([
            'message' => '掌中付回调参数',
            'params' => $params,
        ],'zhang_zhong_fu_pay');
        $message = $this->service->wechatThirdPartyPayCallBack($params);

        echo $message;
        exit();
    }

    // 米花第三方支付回调
    public function thirdPartyCallback1()
    {
        $params = Request::param();
        flog([
            'message' => '米花第三方支付回调参数',
            'params' => $params,
        ],'mihua_pay');
        $message = $this->service->wechatThirdPartyPayCallBack1($params);
        echo $message;
        exit();
    }

    // 米花第三方支付退款回调
    public function mhorderrefundcallback()
    {
        $params = Request::param();
        flog([
            'message' => '米花第三方支付退款回调参数',
            'params' => $params,
        ],'mihua_pay');
        $message = $this->service->mhOrderRefundCallback($params);
        echo $message;
        exit();
    }

    /**
     * 扫码富支付回调
     * @return false|string
     */
    public function saoMaFuCallBack()
    {
        $params = Request::param();
        flog([
            'message' => '扫码富第三方支付回调参数',
            'params' => $params,
        ],'sao_ma_pay_back');
        $result = $this->service->wechatThirdPartySMFCallback($params);
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
        exit();
    }

    /**
     * 扫码富退款回调
     * @return false|string
     */
    public function saoMaFuRefundCallBack()
    {
        $params = Request::param();
        flog([
            'message' => '扫码富第三方退款回调参数',
            'params' => $params,
        ],'sao_ma_refund_back');
        $result = $this->service->wechatThirdPartySMFRefundCallback($params);
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
        exit();
    }

    // 可以自定义  符合token规范即可 同时与微信公众平台对应
    const TOKEN = '46b6444beb88d63b225dd99ac683870f';
 
    /**
     * 比翼鸟剧场公众号关注访问服务器的地址
     */
    public function login()
    {
        $postStr = file_get_contents('php://input');
        // file_put_contents('./public_login.txt', date("Y-m-d H:i:s").' ：'.$postStr.' ; '.PHP_EOL, FILE_APPEND);

        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, NULL, LIBXML_NOCDATA);

        if (strtolower($postObj->MsgType) == 'event' && strtolower($postObj->Event) == 'click') {
            // 自定义菜单的click事件
            $sendBackXml = $this->service->menuClickEvent($postObj);
            echo $sendBackXml;
            exit();
        } else if (strtolower($postObj->MsgType) == 'event') {
            $sendBackXml = $this->service->wechatOfficialAccountLogin($postObj);
            echo $sendBackXml;
            exit(); // 一定要加！！！！不加程序运转正常就是不回复消息
        } else if (strtolower($postObj->MsgType) == 'text') {
            $sendBackXml = $this->service->wechatOfficialAccountCustomReply($postObj);
            echo $sendBackXml;
            exit();
        } else {
            exit();
        }
    }

    // 比翼鸟短剧公众号关注访问服务器的地址
    public function seraphLogin()
    {
        $postStr = file_get_contents('php://input');
        // file_put_contents('./public_login.txt', date("Y-m-d H:i:s").' ：'.$postStr.' ; '.PHP_EOL, FILE_APPEND);

        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, NULL, LIBXML_NOCDATA);

        if (strtolower($postObj->MsgType) == 'event' && strtolower($postObj->Event) == 'click') {
            // 自定义菜单的click事件
            $sendBackXml = $this->service->menuClickEvent($postObj);
            echo $sendBackXml;
            exit();
        } else if (strtolower($postObj->MsgType) == 'event') {
            $sendBackXml = $this->service->wechatOfficialAccountLogin($postObj);
            echo $sendBackXml;
            exit(); // 一定要加！！！！不加程序运转正常就是不回复消息
        } else if (strtolower($postObj->MsgType) == 'text') {
            $sendBackXml = $this->service->wechatOfficialAccountCustomReply($postObj);
            echo $sendBackXml;
            exit();
        } else {
            exit();
        }
    }

    // 微信公众平台服务号访问服务器的地址
    public function officialAccountLogin()
    {
        // $signature = $_GET["signature"];
        // $timestamp = $_GET["timestamp"];
        // $nonce = $_GET["nonce"];

        // $token = self::TOKEN;
        // $tmpArr = array($token, $timestamp, $nonce);
        // sort($tmpArr, SORT_STRING);
        // $tmpStr = implode( $tmpArr );
        // $tmpStr = sha1( $tmpStr );

        // header('content-type:text');
        // // 防止其他输出
        // ob_clean();
        // // 要注意返回的是echostr 而不是 true或者false
        // exit(htmlspecialchars($_GET['echostr']));

        $postStr = file_get_contents('php://input');
        // file_put_contents('./public_login.txt', date("Y-m-d H:i:s").' ：'.$postStr.' ; '.PHP_EOL, FILE_APPEND);

        libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($postStr, NULL, LIBXML_NOCDATA);

        if (strtolower($postObj->MsgType) == 'event' && strtolower($postObj->Event) == 'click') {
            // 自定义菜单的click事件
            $sendBackXml = $this->service->menuClickEvent($postObj);
            echo $sendBackXml;
            exit();
        } else if (strtolower($postObj->MsgType) == 'event') {
            $sendBackXml = $this->service->wechatOfficialAccountLogin($postObj);
            echo $sendBackXml;
            exit(); // 一定要加！！！！不加程序运转正常就是不回复消息
        } else if (strtolower($postObj->MsgType) == 'text') {
            $sendBackXml = $this->service->wechatOfficialAccountCustomReply($postObj);
            echo $sendBackXml;
            exit();
        } else {
            exit();
        }
    }

    /**
     * 微信公众号服务器配置验证 checkSignature
     */
    public function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = self::TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        header('content-type:text');
        // 防止其他输出
        ob_clean();
        // 要注意返回的是echostr 而不是 true或者false
        exit(htmlspecialchars($_GET['echostr']));
    }

    // 获取访问小程序的链接地址(限单个用户使用，限每天50万)
    public function getWxUrl()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Login::class)->scene('get_wx_url')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $data = $this->service->getJumpWxAppletUrl($params);

        if (!empty($data['message'])) {
            return Common::fail($data['message']);
        }

        return Common::success($data);
    }

    /**
     * 小程序消息推送回调
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function appletcallback()
    {
        $params = Request::param();
        flog([
            'message' => '微信小程序回调参数',
            'params' => $params,
        ],'wechat_pay');
        // 用于小程序后台验证token返回
        if (!empty($params['echostr'])){
            echo $params['echostr'];exit;
        }
        //判断请求是否来自于微信小程序官方推送
        if ($this->service->checkSignature($params)){
            flog('微信小程序回调校验成功','wechat_pay');
            $bool = $this->service->appletCallback($params);
            if ($bool){
                flog('微信小程序回调成功','wechat_pay');
                echo 'success';exit;
            }
        }
        flog([
            'message' => '微信小程序回调校验失败',
            'params' => $params,
        ],'wechat_pay','error');
        echo 'fail';exit;
    }
    public function test()
    {
        $data = [
            'type'  => 'new_video_online',//类型
            'thing1' => '财皇的美女总裁老婆',//视频名称
            'thing2' => '财皇的美女总裁老婆',//视频描述
            'time3' => date('Y-m-d H:i:s'),//上线时间
        ];
        $res = WechatSubscribeService::doSend($data);
    }
}